package org.client.iot.util;

import android.util.Log;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * 作者：Administrator on 2020/8/18 10:46
 * 时间工具类
 */
public class TimeUtils {

    private static final String TAG = "TimeUtils:";

    public static String getTime() {
        return formatTime(new Date(),"yyyy-MM-dd HH:mm:ss");
    }
    public static String getTimeNow() {
        return formatTime(new Date(),"yyyy-MM-dd HH:mm");
    }

    public static String getTimeNowLn() {
        return formatTime(new Date(),"yyyy-MM-dd \n HH:mm");
    }

    public static String getTimeNowSimple(){
        return formatTime(new Date(),"yyyy-MM-dd");
    }
    /**
     * 获取查询存储在数据库中时间(精确到秒)
     * @param date
     * @return
     */
    public static String getSQLNowTime(Date date){
        return formatTime(date,"yyyy-MM-dd HH:mm:ss");
    }
    /**
     * 获取查询存储在数据库中时间(精确到秒)
     * @param time
     * @return
     */
    public static String getSimpleTime(String time){
        return formatTime(time,"yyyy-MM-dd hh:mm:ss.SSS");
    }
    /**
     * 获取查询存储在数据库中时间(精确到秒)
     * @param time
     * @return
     */
    public static Date getHHTime(String time){
        return formatTimeToDate(time,"yyyy-MM-dd hh:mm:ss");
    }

    public static String getTimeOnlyDay(String time){
        return formatTime(time,"yyyy-MM-dd");
    }
    public static String getTimeHHss(String time){
        return formatTime(time,"yyyy-MM-dd HH:mm:ss");
    }


    private static String formatTime(Date dates,String match){
        SimpleDateFormat sDateFormat = new SimpleDateFormat(match);
        String date = sDateFormat.format(dates);
        return date;
    }

    public static String getTimeByHHMM(Long time) {
        Date date = new Date(time);
        return formatTime(date,"HH:mm");
    }

    public static String getTimeByAll(Long time) {
        Date date = new Date(time);
        return formatTime(date,"yyyy-MM-dd HH:mm");
    }

    private static String formatTime(String dates,String match){
        SimpleDateFormat sDateFormat = new SimpleDateFormat(match);
        String date = "";
        try {
            Date parse = sDateFormat.parse(dates);
            date = sDateFormat.format(parse);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return date;
    }
    private static Date formatTimeToDate(String dates,String match){
        SimpleDateFormat sDateFormat = new SimpleDateFormat(match);
        Date date = null;
        try {
            date = sDateFormat.parse(dates);
        } catch (ParseException e) {
            Log.d(TAG, "formatTimeToDate: "+e.getCause());
        }
        return date;
    }

    public static String getLastWeek(String time){
        return  minusDay(time,-7);
    }

    public static String getLastDay(String time){
        return minusDay(time,-1);
    }

    public static String minusDay(String time, int minus){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(sdf.parse(time));
        } catch (ParseException e) {
            Log.d(TAG,"时间转换异常:"+e.getCause());
        }
        calendar.add(Calendar.DATE , minus);
        return sdf.format(calendar.getTime());
    }
    /**
     * 获取yyyy-MM-dd 格式的当前日期
     **/
    public static String getYearAndMonthAndDayTime(Date date) {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dates = sDateFormat.format(date);
        return dates;
    }
    public static String formatDateTime(String dateTimeStr) {
        try {
            // 如果是时间戳格式
            if (dateTimeStr.matches("\\d{10,13}")) {
                long timestamp = Long.parseLong(dateTimeStr);
                // 处理秒级时间戳和毫秒级时间戳
                if (dateTimeStr.length() == 10) {
                    timestamp *= 1000;
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                return sdf.format(new Date(timestamp));
            }
            // 如果是其他格式，可以根据实际情况添加处理逻辑
            else if (dateTimeStr.contains("T")) {
                // 处理 ISO 8701 格式 (如: 2025-08-20T14:59:33)
                SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());
                SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                Date date = inputFormat.parse(dateTimeStr);
                return outputFormat.format(date);
            }
            // 如果已经是期望格式，直接返回
            return dateTimeStr;
        } catch (Exception e) {
            // 格式化失败，返回原始值
            return dateTimeStr;
        }
    }

    /**
     * 获取hh:mm 格式的当前日期
     **/
    public static String getMinuteAndSecondTime(String time) {
        SimpleDateFormat mSimpleDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        SimpleDateFormat mHourDate = new SimpleDateFormat("HH:mm");
        String date = "";
        try {
            Date parse = mSimpleDate.parse(time);
            date = mHourDate.format(parse);
        } catch (ParseException e) {
            Log.d(TAG, "getMinuteAndSecondTime: "+e.getCause());
        }
        return date;
    }

    public static boolean isTimeRange(String range) {
        Calendar c = Calendar.getInstance();
        String time = c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + ":00";
        boolean inFirstTime = isInTime(range, time);
        return inFirstTime;
    }
    public static boolean isEveTimeRange(String time) {
        boolean inFirstTime = isInTime("20:00:00-23:59:59", time);
        return inFirstTime;
    }
    public static boolean isAfterNightTimeRange(String time) {
        boolean inFirstTime = isInTime("00:00:00-09:00:00", time);
        return inFirstTime;
    }

    /**
     * 判断某一时间是否在一个区间内
     * <p>
     * 注意：这个实现奇怪的是 "12:00:00" 也判断为 "00:00:00"，例子 System.out.println(isInTime("00:00:00-00:01:00", "12:00:00"));
     *
     * @param sourceTime 时间区间,半闭合,如[10:00-20:00)
     * @param curTime    需要判断的时间 如10:00
     * @return
     * @throws IllegalArgumentException
     */
    public static boolean isInTime(String sourceTime, String curTime) {
        boolean isIn = false;
        String[] sourceArr = sourceTime.split("-");
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        try {
            long mCurTime = sdf.parse(curTime).getTime();
            long startTime = sdf.parse(sourceArr[0]).getTime();
            long endTime = sdf.parse(sourceArr[1]).getTime();
            if (mCurTime >= startTime && mCurTime <= endTime) {
                isIn = true;
            } else {
                isIn = false;
            }
        } catch (ParseException e) {
            Log.d(TAG, "-isInTime方法异常:" + e.getCause());
        }
        return isIn;
    }


    public static long getTotalSleepTime(String start,String end){
        Date startHhTime = getHHTime(start);
        Date endHhTime = getHHTime(end);
        long diff = startHhTime.getTime() - endHhTime.getTime();//这样得到的差值是微秒级别
        long days = diff / (1000 * 60 * 60 * 24);

        long hours = (diff-days*(1000 * 60 * 60 * 24))/(1000* 60 * 60);
        long minutes = (diff-days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60))/(1000* 60);
        long sleepTime = hours * 60 + minutes;
        return sleepTime;
    }

    public static String formatSleepHH(long totalSleepTime) {
        BigDecimal sleepTimeDecimal = BigDecimal.valueOf(totalSleepTime);
        sleepTimeDecimal = sleepTimeDecimal.divide(BigDecimal.valueOf(60),1,BigDecimal.ROUND_HALF_DOWN);
        String res = sleepTimeDecimal.doubleValue()+"h";
        return res;
    }

    public static boolean isSleepTime() {
        Calendar cal = Calendar.getInstance();
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        if(hour>=20 || hour<9){
            return true;
        }
        return false;
    }
}
